import React from 'react';
import {connect} from 'react-redux';
import config from 'config';
import { Badge, Button, Popover } from 'antd';
import menuRoute from 'routes/menuRoute';
import httpFetch from 'share/httpFetch';
import {messages} from "share/common";
import SearchArea from 'components/search-area'
import SlideFrame from 'components/slide-frame'
import NewSubjectSheet from 'containers/setting/subject-sheet/new-subject-sheet';
import ResizeTable from "components/resize-table";

class SubjectSheet extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      data: [],
      pagination: {
        page: 0,
        total: 0,
        pageSize: 10,
      },
      columns: [
        {
          title: messages('setting.key1049'/*科目表代码*/),
          dataIndex: 'accountSetCode',
          width: '20%'
        },
        {
          title: messages('setting.key1051'/*科目表名称*/),
          dataIndex: 'accountSetDesc',
          width: '30%',
          render: accountSetDesc => (
            <Popover content={accountSetDesc}>
              {accountSetDesc}
            </Popover>)
        },
        {
          title: messages('common.column.status'),
          dataIndex: 'enabled',
          width: '6%',
          align: "center",
          render: enabled => (
            <Badge status={enabled ? 'success' : 'error'}
                   text={enabled ? messages('common.status.enable') : messages('common.status.disable')}/>
          )
        },
        {
          title: messages('common.operation')/*操作*/,
          dataIndex: 'operation',
          width: '10%',
          key: "id",
          align: "center",
          render: (text, record) => (
            <div>
             <span>
                <a onClick={(e) => this.editItem(record)}>
                  {/*编辑*/}
                  {messages('common.edit')}
                  </a>
                <span className="ant-divider"/>
                <a style={{marginRight: 10}} onClick={(e) => this.handleRowClick(e, record)}>
                  {/*查看详情*/}
                  {messages('setting.key1061'/*查看详情*/)}
                  </a>
              </span>
            </div>)
        }
      ],
      searchForm: [
        //科目表代码
        {
          type: 'input', id: 'accountSetCode',
          label: messages('setting.key1049'/*科目表代码*/)
        },
        ////科目表描述
        {
          type: 'input', id: 'accountSetDesc',
          label: messages('setting.key1051'/*科目表名称*/)
        }
      ],
      searchParams: {
        accountSetCode: '',
        accountSetDesc: ''
      },
      updateParams: {},
      showSlideFrame: false,
      showSlideFrameNew: false,
      SubjectSheetDetail: menuRoute.getRouteItem('subject-sheet-detail', 'key'),
  };
  }

  componentWillMount() {
    let _pagination = this.getBeforePage();
    let pagination = this.state.pagination;
    pagination.page = _pagination.page;
    pagination.current = _pagination.page + 1;
    this.setState({
      pagination,
    }, () => {
      this.clearBeforePage();
      this.getList();
    })
  }

  editItem = (record) => {
    this.setState({
      updateParams: record,
      showSlideFrame: true
    })
    this.showSlideNew(true);
  };

  //得到列表数据
  getList() {
    this.setState({loading: true});
    let pagination = this.state.pagination;
    let params = this.state.searchParams;
    let url = `${config.baseUrl}/api/account/set/query?&page=${pagination.page}&size=${pagination.pageSize}`;
    for (let paramsName in params) {
      url += params[paramsName] ? `&${paramsName}=${params[paramsName]}` : '';
    }
    return httpFetch.get(url).then((response) => {
      response.data.map((item) => {
        item.key = item.id;
      });
      pagination.total = Number(response.headers['x-total-count']);
      this.setState({
        data: response.data,
        loading: false,
        pagination
      })
    });
  }

  //分页点击
  onChangePager = (p, filters, sorter) => {
    let pagination = this.state.pagination;
    pagination.page = p.current - 1;
    pagination.current = p.current;
    this.setState({
      pagination
    }, () => {
      this.getList();
    })
  };
  //跳转到详情
  handleRowClick = (e, value) => {
    this.setBeforePage(this.state.pagination);
    let path = this.state.SubjectSheetDetail.url.replace(":accountSetId", value.id);
    this.context.router.push(path);
  };

  search = (result) => {
    let pagination = this.state.pagination;
    pagination.page = 0;
    pagination.current = 1;
    this.setState({
      pagination,
      searchParams: {
        accountSetCode: result.accountSetCode ? result.accountSetCode : '',
        accountSetDesc: result.accountSetDesc ? result.accountSetDesc : ''
      }
    }, () => {
      this.getList();
    })
  };

  clear = () => {
    this.setState({
      searchParams: {
        accountSetCode: '',
        accountSetDesc: ''
      }
    })
  };

  handleCloseNewSlide = (params) => {
    if (params) {
      this.getList();
    }
    this.setState({
      showSlideFrameNew: false
    })
  };

  showSlideNew = (flag) => {
    this.setState({
      showSlideFrameNew: flag
    })
  };

  newItemShowSlide = () => {
    this.setState({
      updateParams: {},
    }, () => {
      this.showSlideNew(true)
    })
  };

  render() {
    const { columns, data, loading, pagination, searchForm, updateParams,
      showSlideFrameNew } = this.state;
    return (
      <div className="budget-organization">
        <h3 className="header-title">
          {/*预算组织定义*/}
          {messages('setting.key1062'/*科目表定义*/)}
        </h3>
        <SearchArea
          searchForm={searchForm}
          submitHandle={this.search}
          clearHandle={this.clear}
        />
        <div className="table-header">
          <div className="table-header-title">
            {messages('common.total', {total: pagination.total ? pagination.total : '0'})}
            </div>
          {/* 共total条数据 */}
          <div className="table-header-buttons">
            <Button type="primary"
                    onClick={this.newItemShowSlide}>
              {/*新建*/}
              {messages('common.create')}</Button>
          </div>
        </div>
        <ResizeTable
          columns={columns}
          dataSource={data}
          pagination={pagination}
          onChange={this.onChangePager}
          loading={loading}
          bordered
          size="middle"
        />
        {/* 编辑科目表 */}
        {/*新建科目表:编辑科目表*/}
        <SlideFrame
          title={JSON.stringify(updateParams) === "{}" ? messages('setting.key1063'/*新建科目表*/): messages('setting.key1064'/*编辑科目表*/)}
          show={showSlideFrameNew}
          content={NewSubjectSheet}
          afterClose={this.handleCloseNewSlide}
          onClose={() => this.setState({showSlideFrameNew: false})}
          params={updateParams}/>
      </div>
    )
  }

}

SubjectSheet.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps() {
  return {}
}

export default connect(mapStateToProps)(SubjectSheet);
